import axios from 'axios'
import type { InternalAxiosRequestConfig, AxiosResponse } from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useAuth } from '@/stores/index'
import { getSignatureParam } from './auth'

// 创建 axios 实例
const service = axios.create({
    baseURL: import.meta.env.DEV ? import.meta.env.VITE_APP_BASE_API : import.meta.env.VITE_APP_API_URL,
    timeout: 50000,
    headers: { 'Content-Type': 'application/jsoncharset=utf-8' },
})

// 请求拦截器
service.interceptors.request.use(
    (config: InternalAxiosRequestConfig) => {
        const { token } = storeToRefs(useAuth())
        if (token.value) {
            config.headers.Authorization = token.value
            config.headers["x-Ins-Token"] = token.value
        }
        const { timestamp, signature, nonceStr } = getSignatureParam()
        config.headers["X-Ins-Timestamp"] = timestamp
        config.headers["X-Ins-Signature"] = signature
        config.headers["X-Ins-Nonce"] = nonceStr
        return config
    },
    (error: any) => {
        return Promise.reject(error)
    }
)

// 响应拦截器
service.interceptors.response.use(
    (response: AxiosResponse) => {
        // 检查配置的响应类型是否为二进制类型（'blob' 或 'arraybuffer'）, 如果是，直接返回响应对象
        if (
            response.config.responseType === "blob" ||
            response.config.responseType === "arraybuffer"
        ) {
            return response;
        }
        // 响应数据为二进制流处理(Excel导出)
        if (response.data instanceof ArrayBuffer) {
            return response
        }

        const { code, msg } = response.data
        const { clearToken } = useAuth()



        if (code === 1) {
            return response.data
        }

        // token 过期,重新登录
        if (code === 401) {
            ElMessageBox.confirm('请重新登录', '提示', {
                confirmButtonText: '确定',
                type: 'warning',
            }).finally(() => {
                clearToken()
            })
            ElMessage.error(msg || '系统出错')
            return Promise.reject(new Error(msg || 'Error'))
        }

        ElMessage.error(msg || '系统出错')
        return Promise.reject(new Error(msg || 'Error'))
    }, (error: any) => {
        if (error.response.data) {
            const { msg } = error.response.data

            ElMessage.error(msg || '系统出错')
        }
        return Promise.reject(error.message)
    }
)

// 导出 axios 实例
export default service
